import markdownIt from 'markdown-it'
// markdown转html
const markdown = new markdownIt()
markdown.set({
    html: true,
    linkify: true,
    typographer: true,
    breaks: true,
    xhtmlOut: true
})
export const markdownToHtml = (markdownStr) => {
    return markdown.render(markdownStr)
}

// 时间格式化
export const getCurrentFormattedTime = (d) => {
    const now = d ? new Date(d * 1000) : new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要+1，并补零
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

/**
 * XSS 防护辅助函数 对 str 进行转义处理，确保不会引入恶意脚本
 * @param str
 */
export const escapeHtml = (unsafe) => {
    return unsafe.replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

/**
 * unicode转字符
 * @param text
 */
export const unicodeToChar = (text) => {
    if (!text)
        return ''

    return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
        return String.fromCharCode(parseInt(p1, 16))
    })
}